package hn.cch.advanced.concurrent;


import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class CyclicBarrierDemo {

    public static void main(String[] args) {
        int n = 3;
        ExecutorService threadPool = Executors.newFixedThreadPool(n);

        CyclicBarrier cyclicBarrier = new CyclicBarrier(n, new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + ":ready");
            }
        });

        for (int i = 0; i < n; i++) {
            threadPool.execute(() -> {
                System.out.println(Thread.currentThread().getName() + ":begin");
                try {
                    Thread.sleep((long) (Math.random() * 10000));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + ":end");
                try {
                    // 等待其他线程同事到达栅栏
                    cyclicBarrier.await();// 内部调用dowait方法
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + ":start");

            });
        }

        // cyclicBarrier.reset(); // 重置，可重复使用
        System.out.println(Thread.currentThread().getName() + ":ready");
        threadPool.shutdown(); // 处理线程池在任务没有执行完成之前main函数结束（守护线程数）
        ExecutorServiceUtil.complete(threadPool);

    }
}
